package cash.cmp.personal_financial_system.utils.easyexcel.listener;

import cash.cmp.personal_financial_system.model.Bill;
import cash.cmp.personal_financial_system.service.impl.BillServiceImpl;
import cash.cmp.personal_financial_system.utils.shrioUtil.PwdUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Transactional(rollbackFor = Exception.class)
public class BillExcelListener extends AnalysisEventListener<Bill> {

    //用来记录当前记录条数
    Integer index = 0;
    //确认上传用户
    private Integer id;

    private List<Bill> list = new ArrayList<>();
    /**
     * 每隔100条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    //记录未导入信息的错误
    private List<String> msgList;

    private static final String errorTitle = "未导入";

    private BillServiceImpl billService;

    public BillExcelListener(BillServiceImpl billService,Integer id,List<String> msgList) {
        this.billService = billService;
        this.id = id;
        this.msgList = msgList;
    }

    @Override
    public void invoke(Bill bill, AnalysisContext analysisContext) {
        // 数据存储到datas，供批量处理，或后续自己业务逻辑处理。
        //这里做数据校验
        if(vertify(bill)) {
            bill.setId(id);
            Date dNow = new Date( );
            SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS");
            String billId = bill.getId() + "," +  ft.format(dNow)+ "," + PwdUtil.genRandomPwd(8);
            bill.setBillId(billId);
            if (bill.getInsertionTime() == null)
                bill.setInsertionTime(dNow);
            list.add(bill);
            System.out.println("解析到一条数据:========================"+bill.toString());
        }
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if(list.size() >= BATCH_COUNT){
            saveData();
            // 存储完成清理datas
            list.clear();
        }
    }
    /**
     * 所有数据解析完成了 都会来调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        if(list.size() > 0) {
            System.out.println("==============================" + list.size() + "条数据，开始存储到数据库");
            billService.saveList(list);
        }
    }
    /**
     * 对excel文件内的bill进行校验
     */
    public Boolean vertify(Bill bill){
        Boolean flag = true;
        index++;
        String temp = errorTitle + "第" + index + "条数据,错误为：";
        if(bill.getBillName() == null){
            flag = false;
            temp += "账单名为空 ";
        }
        if(bill.getType() == null){
            flag = false;
            temp += "记账类型为空 ";
        }
        if(bill.getMoney() == 0){
            flag = false;
            temp += "记账金额为空 ";
        }
        if(bill.getTime() == null){
            flag = false;
            temp += "记账时间为空 ";
        }
        if(flag){
            return true;
        }
        else {
            msgList.add(temp);
            return false;
        }
    }
}
